/**
 * 患者管理页面脚本
 * 负责患者列表的交互功能、筛选、分页和模态框操作
 */

document.addEventListener('DOMContentLoaded', function() {
    // 初始化UI组件
    initUI();
    
    // 初始化患者数据
    initPatientData();
    
    // 设置事件监听器
    setupEventListeners();
});

/**
 * 初始化UI组件
 */
function initUI() {
    // 使用模态框管理器
    window.patientModal = modalManager.openModal;
    window.closePatientModal = modalManager.closeModal;
}

/**
 * 初始化患者表格数据
 */
function initPatientData() {
    // 模拟数据（实际项目中会从服务器获取）
    const patients = [
        {
            id: 'P100001',
            name: '张三',
            gender: '男',
            age: 45,
            phone: '13812345678',
            doctor: '王医生',
            department: '内科',
            lastVisit: '2023-06-15',
            status: '活跃'
        },
        {
            id: 'P100002',
            name: '李四',
            gender: '女',
            age: 32,
            phone: '13987654321',
            doctor: '赵医生',
            department: '妇产科',
            lastVisit: '2023-06-10',
            status: '待诊'
        },
        {
            id: 'P100003',
            name: '王五',
            gender: '男',
            age: 56,
            phone: '15698765432',
            doctor: '李医生',
            department: '神经科',
            lastVisit: '2023-05-22',
            status: '非活跃'
        },
        {
            id: 'P100004',
            name: '赵六',
            gender: '女',
            age: 28,
            phone: '13765432109',
            doctor: '张医生',
            department: '外科',
            lastVisit: '2023-06-18',
            status: '已出院'
        }
    ];
    
    // 渲染患者表格
    renderPatientTable(patients);
}

/**
 * 渲染患者表格
 * @param {Array} patients - 患者数据数组
 */
function renderPatientTable(patients) {
    const tbody = document.getElementById('patientsTableBody');
    if (!tbody) return;
    
    // 清空表格
    tbody.innerHTML = '';
    
    // 渲染每一行
    patients.forEach(patient => {
        const tr = document.createElement('tr');
        
        // 设置状态样式类
        let statusClass = '';
        switch (patient.status) {
            case '活跃': statusClass = 'active'; break;
            case '非活跃': statusClass = 'inactive'; break;
            case '待诊': statusClass = 'waiting'; break;
            case '已出院': statusClass = 'discharged'; break;
        }
        
        // 设置行内容
        tr.innerHTML = `
            <td><input type="checkbox" class="select-row"></td>
            <td>${patient.id}</td>
            <td class="patient-name">
                <div class="avatar sm"><span>${patient.name.charAt(0)}</span></div>
                <span>${patient.name}</span>
            </td>
            <td>${patient.gender}</td>
            <td>${patient.age}</td>
            <td>${patient.phone}</td>
            <td>${patient.doctor}</td>
            <td>${patient.department}</td>
            <td>${patient.lastVisit}</td>
            <td><span class="status-badge ${statusClass}">${patient.status}</span></td>
            <td class="actions">
                <button class="btn-icon" title="查看详情" data-action="view" data-id="${patient.id}">
                    <span data-icon="view"></span>
                </button>
                <button class="btn-icon" title="编辑" data-action="edit" data-id="${patient.id}">
                    <span data-icon="edit"></span>
                </button>
                <button class="btn-icon" title="删除" data-action="delete" data-id="${patient.id}">
                    <span data-icon="delete"></span>
                </button>
            </td>
        `;
        
        // 添加到表格
        tbody.appendChild(tr);
    });
    
    // 初始化图标
    iconManager.replaceAll();
    
    // 设置行操作按钮事件
    setupRowActions();
}

/**
 * 设置事件监听器
 */
function setupEventListeners() {
    // 用户下拉菜单
    setupUserMenu();
    
    // 侧边栏切换
    setupSidebar();
    
    // 复选框全选/取消全选
    setupCheckboxes();
    
    // 筛选功能
    setupFilters();
    
    // 搜索功能
    setupSearch();
    
    // 模态框操作
    setupModals();
    
    // 分页功能
    setupPagination();
    
    // 导出功能
    setupExport();
}

/**
 * 设置用户菜单
 */
function setupUserMenu() {
    const userMenuBtn = document.getElementById('userMenuBtn');
    const userDropdown = document.getElementById('userDropdown');
    
    if (userMenuBtn && userDropdown) {
        userMenuBtn.addEventListener('click', function(e) {
            e.stopPropagation();
            userDropdown.classList.toggle('active');
        });
        
        // 点击页面其他区域关闭下拉菜单
        document.addEventListener('click', function() {
            userDropdown.classList.remove('active');
        });
    }
}

/**
 * 设置侧边栏
 */
function setupSidebar() {
    const sidebarToggle = document.getElementById('sidebarToggle');
    const sidebar = document.querySelector('.sidebar');
    
    if (sidebarToggle && sidebar) {
        sidebarToggle.addEventListener('click', function() {
            sidebar.classList.toggle('collapsed');
            document.querySelector('.main-content').classList.toggle('expanded');
        });
    }
}

/**
 * 设置复选框功能
 */
function setupCheckboxes() {
    const selectAllCheckbox = document.getElementById('selectAll');
    if (!selectAllCheckbox) return;
    
    selectAllCheckbox.addEventListener('change', function() {
        const rowCheckboxes = document.querySelectorAll('.select-row');
        rowCheckboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
        });
    });
    
    // 监听单个复选框变化
    document.addEventListener('change', function(e) {
        if (e.target && e.target.classList.contains('select-row')) {
            updateSelectAllState();
        }
    });
}

/**
 * 更新全选框状态
 */
function updateSelectAllState() {
    const selectAllCheckbox = document.getElementById('selectAll');
    if (!selectAllCheckbox) return;
    
    const totalCheckboxes = document.querySelectorAll('.select-row').length;
    const checkedCheckboxes = document.querySelectorAll('.select-row:checked').length;
    
    selectAllCheckbox.checked = totalCheckboxes > 0 && totalCheckboxes === checkedCheckboxes;
    selectAllCheckbox.indeterminate = checkedCheckboxes > 0 && checkedCheckboxes < totalCheckboxes;
}

/**
 * 设置筛选功能
 */
function setupFilters() {
    const departmentFilter = document.getElementById('departmentFilter');
    const statusFilter = document.getElementById('statusFilter');
    
    if (departmentFilter) {
        departmentFilter.addEventListener('change', filterPatients);
    }
    
    if (statusFilter) {
        statusFilter.addEventListener('change', filterPatients);
    }
}

/**
 * 筛选患者列表
 */
function filterPatients() {
    const department = document.getElementById('departmentFilter').value;
    const status = document.getElementById('statusFilter').value;
    const rows = document.querySelectorAll('.data-table tbody tr');
    
    rows.forEach(row => {
        let showRow = true;
        
        // 科室筛选
        if (department && row.querySelector('td:nth-child(8)').textContent !== department) {
            showRow = false;
        }
        
        // 状态筛选
        if (status && row.querySelector('.status-badge').textContent !== status) {
            showRow = false;
        }
        
        row.style.display = showRow ? '' : 'none';
    });
    
    // 更新分页信息
    updatePagination();
}

/**
 * 更新分页信息
 */
function updatePagination() {
    // 简化版 - 实际项目中可能需要重新加载数据
    console.log('分页信息已更新');
}

/**
 * 设置搜索功能
 */
function setupSearch() {
    const searchInput = document.querySelector('.search-box input');
    
    if (searchInput) {
        searchInput.addEventListener('input', function() {
            const searchTerm = this.value.toLowerCase();
            const rows = document.querySelectorAll('.data-table tbody tr');
            
            rows.forEach(row => {
                const patientName = row.querySelector('td:nth-child(3)').textContent.toLowerCase();
                const patientId = row.querySelector('td:nth-child(2)').textContent.toLowerCase();
                const phoneNumber = row.querySelector('td:nth-child(6)').textContent.toLowerCase();
                
                const matchesSearch = patientName.includes(searchTerm) || 
                                     patientId.includes(searchTerm) || 
                                     phoneNumber.includes(searchTerm);
                
                row.style.display = matchesSearch ? '' : 'none';
            });
            
            updatePagination();
        });
    }
}

/**
 * 设置模态框功能
 */
function setupModals() {
    const addPatientBtn = document.getElementById('addPatientBtn');
    const addPatientModal = document.getElementById('addPatientModal');
    const cancelAddPatientBtn = document.getElementById('cancelAddPatient');
    const savePatientBtn = document.getElementById('savePatient');
    
    // 打开添加患者模态框
    if (addPatientBtn && addPatientModal) {
        addPatientBtn.addEventListener('click', function() {
            const patientForm = document.getElementById('patientForm');
            if (patientForm) patientForm.reset();
            modalManager.openModal(addPatientModal);
        });
    }
    
    // 取消按钮
    if (cancelAddPatientBtn) {
        cancelAddPatientBtn.addEventListener('click', function() {
            modalManager.closeModal(addPatientModal);
        });
    }
    
    // 保存患者信息
    if (savePatientBtn) {
        savePatientBtn.addEventListener('click', function() {
            const patientForm = document.getElementById('patientForm');
            if (!patientForm) return;
            
            // 验证表单
            if (!patientForm.checkValidity()) {
                patientForm.reportValidity();
                return;
            }
            
            // 收集表单数据
            const formData = new FormData(patientForm);
            const patientData = {
                patientName: formData.get('patientName'),
                patientGender: formData.get('patientGender'),
                patientAge: formData.get('patientAge'),
                patientPhone: formData.get('patientPhone'),
                patientDoctor: formData.get('patientDoctor'),
                patientDepartment: formData.get('patientDepartment')
            };
            
            // 添加患者
            addPatient(patientData);
            
            // 关闭模态框
            modalManager.closeModal(addPatientModal);
        });
    }
}

/**
 * 添加新患者
 * @param {Object} patientData - 患者数据
 */
function addPatient(patientData) {
    // 创建患者对象
    const patient = {
        id: 'P' + (100000 + Math.floor(Math.random() * 900000)),
        name: patientData.patientName || '',
        gender: patientData.patientGender || '',
        age: patientData.patientAge || '',
        phone: patientData.patientPhone || '',
        doctor: patientData.patientDoctor || '',
        department: patientData.patientDepartment || '',
        lastVisit: new Date().toISOString().split('T')[0],
        status: '活跃'
    };
    
    // 获取当前患者列表
    const tbody = document.getElementById('patientsTableBody');
    if (!tbody) return;
    
    // 创建新行
    const tr = document.createElement('tr');
    
    // 设置行内容
    tr.innerHTML = `
        <td><input type="checkbox" class="select-row"></td>
        <td>${patient.id}</td>
        <td class="patient-name">
            <div class="avatar sm"><span>${patient.name.charAt(0)}</span></div>
            <span>${patient.name}</span>
        </td>
        <td>${patient.gender}</td>
        <td>${patient.age}</td>
        <td>${patient.phone}</td>
        <td>${patient.doctor}</td>
        <td>${patient.department}</td>
        <td>${patient.lastVisit}</td>
        <td><span class="status-badge active">${patient.status}</span></td>
        <td class="actions">
            <button class="btn-icon" title="查看详情" data-action="view" data-id="${patient.id}">
                <span data-icon="view"></span>
            </button>
            <button class="btn-icon" title="编辑" data-action="edit" data-id="${patient.id}">
                <span data-icon="edit"></span>
            </button>
            <button class="btn-icon" title="删除" data-action="delete" data-id="${patient.id}">
                <span data-icon="delete"></span>
            </button>
        </td>
    `;
    
    // 将新行添加到表格开头
    tbody.insertBefore(tr, tbody.firstChild);
    
    // 初始化图标
    iconManager.replaceAll();
    
    // 更新全选框状态
    updateSelectAllState();
    
    // 设置行操作按钮事件
    setupRowActions();
}

/**
 * 设置行操作按钮事件
 */
function setupRowActions() {
    // 使用事件委托处理所有行操作
    document.querySelector('.data-table').addEventListener('click', function(e) {
        // 查找最近的按钮元素
        const button = e.target.closest('.btn-icon');
        if (!button) return;
        
        const action = button.getAttribute('data-action');
        const patientId = button.getAttribute('data-id');
        const row = button.closest('tr');
        const patientName = row.querySelector('.patient-name span').textContent;
        
        switch (action) {
            case 'view':
                // 查看患者详情
                alert(`查看患者详情：${patientName} (${patientId})`);
                break;
                
            case 'edit':
                // 编辑患者信息
                alert(`编辑患者信息：${patientName} (${patientId})`);
                break;
                
            case 'delete':
                // 删除患者
                confirmDialog(`确定要删除患者 ${patientName} (${patientId}) 吗？`, {
                    onConfirm: () => {
                        row.remove();
                        updateSelectAllState();
                    }
                });
                break;
        }
    });
}

/**
 * 设置分页功能
 */
function setupPagination() {
    const paginationButtons = document.querySelectorAll('.pagination-number');
    const prevPageBtn = document.querySelector('.pagination-btn:first-child');
    const nextPageBtn = document.querySelector('.pagination-btn:last-child');
    
    // 分页切换
    paginationButtons.forEach(button => {
        button.addEventListener('click', function() {
            document.querySelector('.pagination-number.active').classList.remove('active');
            this.classList.add('active');
            
            const pageNumber = this.textContent;
            console.log(`加载第 ${pageNumber} 页数据`);
            
            updatePaginationButtons();
        });
    });
    
    // 上一页按钮
    if (prevPageBtn) {
        prevPageBtn.addEventListener('click', function() {
            if (this.disabled) return;
            
            const activePage = document.querySelector('.pagination-number.active');
            const prevPage = activePage.previousElementSibling;
            
            if (prevPage && prevPage.classList.contains('pagination-number')) {
                activePage.classList.remove('active');
                prevPage.classList.add('active');
                
                console.log(`加载第 ${prevPage.textContent} 页数据`);
                updatePaginationButtons();
            }
        });
    }
    
    // 下一页按钮
    if (nextPageBtn) {
        nextPageBtn.addEventListener('click', function() {
            if (this.disabled) return;
            
            const activePage = document.querySelector('.pagination-number.active');
            let nextPage = activePage.nextElementSibling;
            
            // 跳过省略号
            if (nextPage && nextPage.classList.contains('pagination-ellipsis')) {
                nextPage = nextPage.nextElementSibling;
            }
            
            if (nextPage && nextPage.classList.contains('pagination-number')) {
                activePage.classList.remove('active');
                nextPage.classList.add('active');
                
                console.log(`加载第 ${nextPage.textContent} 页数据`);
                updatePaginationButtons();
            }
        });
    }
    
    // 初始化分页按钮状态
    updatePaginationButtons();
}

/**
 * 更新分页按钮状态
 */
function updatePaginationButtons() {
    const prevPageBtn = document.querySelector('.pagination-btn:first-child');
    const nextPageBtn = document.querySelector('.pagination-btn:last-child');
    
    if (!prevPageBtn || !nextPageBtn) return;
    
    const activePage = document.querySelector('.pagination-number.active');
    const firstPage = document.querySelector('.pagination-number:first-of-type');
    const lastPage = document.querySelector('.pagination-number:last-of-type');
    
    // 如果当前页是第一页，禁用上一页按钮
    prevPageBtn.disabled = activePage === firstPage;
    
    // 如果当前页是最后一页，禁用下一页按钮
    nextPageBtn.disabled = activePage === lastPage;
}

/**
 * 设置导出功能
 */
function setupExport() {
    const exportBtn = document.getElementById('exportBtn');
    
    if (exportBtn) {
        exportBtn.addEventListener('click', function() {
            // 实际项目中，这里会发起一个下载请求
            alert('导出患者数据功能将在实际系统中实现');
        });
    }
} 